//
//  AllphotoViewControll.m
//  03 PhotoKit
//
//  Created by liyoubing on 16/5/24.
//  Copyright © 2016年 liyoubing. All rights reserved.
//

#import "AllphotoViewControll.h"
#import "ImageCell.h"
#import <Photos/Photos.h>

@interface AllphotoViewControll ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout> {
    
    UICollectionView *_collectionView;
    
    PHFetchResult *_result;
    PHImageManager *_manager;
}

@end

@implementation AllphotoViewControll

- (void)viewDidLoad {

    [super viewDidLoad];
    
    [self _initCollectionView];
    
    //加载数据
    [self _loadData];
}

- (void)_initCollectionView {

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(90, 90);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    [_collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"ImageCell"];
}

//加载数据
- (void)_loadData {

    //获取图片的资源，设置资源参数
    PHFetchOptions *allOptions = [[PHFetchOptions alloc] init];
    allOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
    
    _result = [PHAsset fetchAssetsWithOptions:allOptions];

    _manager = [PHImageManager defaultManager];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _result.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPath];
    
    //设置cell显示的图片
    PHAsset *asset = _result[indexPath.row];
    
    [_manager requestImageForAsset:asset targetSize:CGSizeMake(90, 90) contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        
        cell.img = result;
        
    }];
    
    return cell;
}


@end
